package com.java.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.mapper.AskMapper;
import com.java.po.Ask;
import com.java.po.AskMap;
import com.java.service.AskService;
import com.java.tool.AjaxJson;

public class AskServiceImpl implements AskService{

	@Autowired
	private AskMapper askMapper;
	private AjaxJson ajaxJson;
	
	
	@SuppressWarnings("resource")
	public AskServiceImpl(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext-dao.xml");
		askMapper = (AskMapper) applicationContext.getBean("askMapper");		
		ajaxJson = new AjaxJson();
	}
	
	public void cleanAjaxJson(){
		ajaxJson.setData("");
		ajaxJson.setTotal(0);
		/*ajaxJson.setAsk("");*/
	}
	@Override
	public AjaxJson insertAsk(Ask ask) throws Exception {
		// TODO Auto-generated method stub
	
		int flag = askMapper.insertAsk(ask);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson deleteAskById(Ask ask) throws Exception {
		// TODO 自动生成的方法存根
				cleanAjaxJson();
				// TODO 自动生成的方法存根
				int flag =askMapper.deleteAsk(ask);
				if(flag!=1){
					ajaxJson.setMessage("fault");
					return ajaxJson;
				}
				ajaxJson.setMessage("success");
				return ajaxJson;
	}

	@Override
	public AjaxJson updateAskById(Ask ask) throws Exception {
		cleanAjaxJson();
		// TODO 自动生成的方法存根
		int flag = askMapper.updateAsk(ask);
		if(flag!=1){
			ajaxJson.setMessage("fault");
			return ajaxJson;
		}
		ajaxJson.setMessage("success");
		return ajaxJson;
	}

	@Override
	public AjaxJson findAllAsk(AskMap askMap) throws Exception {
		// TODO 自动生成的方法存根
				cleanAjaxJson();
				// TODO 自动生成的方法存根
				Ask ask =new Ask();
				int page = askMap.getPage();
				int pageSize = askMap.getPageSize();
				if(askMap.getAsk()!=null){
					ask = askMap.getAsk();
				}
				PageHelper.startPage(page,pageSize);
				List<Ask> list = askMapper.findAllAsk(ask);
				PageInfo<Ask> pageInfo = new PageInfo<>(list);
				ajaxJson.setData(pageInfo.getList());
				ajaxJson.setTotal((int)pageInfo.getTotal());
				return ajaxJson;
	}

	@Override
	public AjaxJson findAskByid(Ask ask) throws Exception {
		// TODO 自动生成的方法存根
				cleanAjaxJson();
				// TODO 自动生成的方法存根
				ask =askMapper.findAskByid(ask);
			    ajaxJson.setData(ask);
				ajaxJson.setTotal(1);
				ajaxJson.setMessage("success");
				return ajaxJson;
	}

}
